package com.imooc.interceptor;

import com.imooc.utils.IPUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 *
 * @auther Levi
 * @Date: 2021/03/20/20:58
 * @Description:    如果前端重新打开一个页面没有携带cookie的话需要后端获取
 */
public class ArticleReadInterceptor extends BaseInterceptor implements HandlerInterceptor {

    /**
     * 拦截器功能：
     *         判断用户是否读过这篇文章
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        String ip = IPUtil.getRequestIp(request);
        String articleId = request.getParameter("articleId");
        String alreadyRead = redis.get(REDIS_ALREADY_READ + ":" + articleId + ":" + ip);
        if (!StringUtils.isEmpty(alreadyRead)) {
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler, Exception ex) throws Exception {

    }
}
